package com.ds.infrastructure.audit.collector.controller;

import com.ds.infrastructure.audit.collector.config.SSOConfig;
import com.ds.infrastructure.audit.collector.entity.UserInfo;
import com.ds.infrastructure.audit.collector.service.SSOService;
import com.ds.infrastructure.audit.collector.util.RequestUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.ServletRequest;

/**
 * @date 2020/8/3
 */
@RestController
@RequestMapping("/api/sso")
@Slf4j
public class SSOController {

    private final SSOConfig ssoConfig;
    private final SSOService ssoService;

    public SSOController(SSOConfig ssoConfig, SSOService ssoService) {
        this.ssoConfig = ssoConfig;
        this.ssoService = ssoService;
        log.info("==== SSO Config={}", ssoConfig.toString());
    }

    @GetMapping
    public SSOInfo ssoInfo() {
        return new SSOInfo(ssoConfig.getService(), ssoConfig.getLoginUrl());
    }

    @GetMapping("/userInfo")
    public UserInfo userInfo(ServletRequest request) {
        UserInfo userInfo = RequestUtils.getUserInfo(request);
        if (userInfo == null) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
        }
        return userInfo;
    }

    @GetMapping("/callback")
    public Sid callback(@RequestParam String ticket) {
        log.info("====SSO callback with ticket: {}", ticket);
        String sid = ssoService.validateTicket(ticket);
        if (sid == null) {
            log.warn("====Not Auth");
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
        }
        return new Sid(sid);
    }

    @Data
    private static class SSOInfo {
        private final String service;
        private final String url;
    }

    @Data
    private static class Sid {
        private final String sid;
    }
}
